<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="6" :md="12" :sm="24">
            <a-form-item label="商家手机">
              <a-input-number style="width:100%" placeholder="请输入手机号" v-model="queryParam.mobile" ></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="12" :sm="24">
            <a-form-item label="商家名称">
              <a-input placeholder="请输入商家名称" v-model="queryParam.name" ></a-input>
            </a-form-item>
          </a-col>
           <a-col :xl="6" :lg="6" :md="12" :sm="24">
            <a-form-item label="代办人姓名/手机">
              <a-input placeholder="请输入姓名/手机" v-model="queryParam.from" ></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="12" :sm="24">
            <a-form-item label="入驻时间筛选">
              <a-range-picker @change="panelChange" v-model="queryParamRangePicker"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="12" :sm="24">
            <a-form-item label="一级类目">
              <a-select default-value="1" placeholder="全部类目" v-model="queryParam.catId" >
                <a-select-option :value="item.val" v-for="(item, index) in catUl" :key="index" >{{ item.name }}</a-select-option >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="12" :sm="24">
            <a-form-item label="状态">
              <a-select default-value="1" placeholder="全部状态" v-model="queryParam.status" >
                <a-select-option :value="item.val" v-for="(item, index) in statusUl" :key="index" >{{ item.name }}</a-select-option >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="3" :lg="3" :md="8" :sm="8">
            <a-form-item label="省">
              <a-select default-value="1" placeholder="全部省" v-model="queryParam.provinceId" @change="provinceIdChange">
                <a-select-option :value="item.val" v-for="(item, index) in provinceUl" :idt="item.id" :key="index" >{{ item.name }}</a-select-option >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="3" :lg="3" :md="8" :sm="8">
            <a-form-item label="市">
              <a-select default-value="1" placeholder="全部市" v-model="queryParam.cityId" @change="cityIdChange">
                <a-select-option :value="item.val" v-for="(item, index) in cityUl" :idt="item.id" :key="index" >{{ item.name }}</a-select-option >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="3" :lg="3" :md="8" :sm="8">
            <a-form-item label="区">
              <a-select default-value="1" placeholder="全部区" v-model="queryParam.districtId"  @change="districtIdChange">
                <a-select-option :value="item.val" v-for="(item, index) in districtUl" :idt="item.id" :key="index" >{{ item.name }}</a-select-option >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="3" :lg="3" :md="8" :sm="8">
            <a-form-item label="商圈">
              <a-select default-value="1" placeholder="全部商圈" v-model="queryParam.businessAreaId" >
                <a-select-option :value="item.val" v-for="(item, index) in businessUl" :key="index" >{{ item.name }}</a-select-option >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="12" :sm="24">
            <a-form-item label="商家等级">
              <a-select default-value="1" placeholder="全部状态" v-model="queryParam.grade" >
                <a-select-option :value="item.val" v-for="(item, index) in gradeUl" :key="index" >{{ item.name }}</a-select-option >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="12" :sm="24">
            <a-form-item label="客服名称">
              <a-select default-value="1" placeholder="全部客服" v-model="queryParam.userId" >
                <a-select-option :value="item.val" v-for="(item, index) in serviceUl" :key="index" >{{ item.name }}</a-select-option >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="24" :lg="24" :md="24" :sm="24">
            <div class="tag_box">
              <div class="tag_box_flex">
                <div class="tag_box_flex_title">
                  <span class="tag_box_title">商家标签：</span>
                </div>
                <div class="tag_box_flex_li" :class="!tagShow ? 'tag_box_flex_show':''">
                  <span class="tag_box_flex_btn" id="tag_box_flex_btn">
                    <a-button 
                    class="tag_button"
                    v-for="(item , index) in tagUl" 
                    size="small"
                    :key="index" 
                    :type="item.choose ? 'primary' : '' " 
                    @click="handleTagsChange(index)"> {{item.name}} </a-button>
                    <a-button size="small" id="tag_show_btn1" class="tag_show_btn1" type="primary" @click="funTagShow" v-show="!tagShow">展开</a-button>
                    <a-button size="small" id="tag_show_btn2" type="primary" @click="funTagShow" v-show="tagShow">收起</a-button>
                  </span>
                </div>
              </div>
            </div>
          </a-col>
          <a-col :xl="24" :lg="24" :md="24" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons" >
              <a-button type="primary" @click="searchQuery" icon="search" >查询</a-button >
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px" >重置</a-button >
              <a-button type="primary" @click="searchExport" icon="upload" style="margin-left: 8px" :loading="confirmLoading">导出</a-button >
              <a-button type="primary" @click="updateUserId" icon="deployment-unit" style="margin-left: 8px" :disabled="selectedRowKeys.length == 0">分配客服</a-button >
              <a-button type="primary" @click="updateTagId" icon="deployment-unit" style="margin-left: 8px" :disabled="selectedRowKeys.length == 0">分配标签</a-button >
              <a-button type="primary" @click="setGrade" icon="deployment-unit" style="margin-left: 8px;" :style="selectedRowKeys.length == 0 ? '' : 'background-color: #D19448;border-color: #D19448;' " :disabled="selectedRowKeys.length == 0">优选店铺</a-button >
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->

    <!-- table区域-begin -->
    <div>
      <a-spin :spinning="confirmLoading">
        <a-table 
          ref="table" 
          size="middle" 
          bordered 
          rowKey="id" 
          :scroll="{ x: 1300 }"
          :columns="columns" 
          :dataSource="tableData" 
          :pagination="ipagination" 
          :loading="loading" 
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          @change="handleTableChange" >
          <!--操作-->
          <span slot="action" slot-scope="text, record" >
            <a-button type="primary" @click="handleDetail(record)">详情</a-button>
            <a-button type="primary" @click="handleBranch(record)">分店</a-button>
            <a-popconfirm title="确认重置为meizhong?" ok-text="确定" cancel-text="取消" :disabled="record.status == 2" @confirm="handlePwd(record.id)">
              <a-button type="primary" :disabled="record.status == 2">重置密码</a-button>
            </a-popconfirm>
            <!-- 暂时隐藏 <a-popconfirm title="确认删除?" ok-text="确定" cancel-text="取消" @confirm="crudDelete(record.id)">
              <a-button type="danger" icon="delete"></a-button>
            </a-popconfirm> -->
          </span>
          <!--图片预览块-->
          <span slot="imgPath" slot-scope="text, record">
            <img :src="record.img" width="100px" height="100px" />
          </span>
          <!--类目-->
          <span slot="catList" slot-scope="text, record">
            <a-tag class="cat_li" color="blue" v-for="(item,index) in record.catList" :key="index">{{item}}</a-tag>
          </span>
          <!--标签-->
          <span slot="tagList" slot-scope="text, record">
            <a-tag class="tag_li" color="green" v-for="(item,index) in record.tagList" :key="index">{{item}}</a-tag>
          </span>
        </a-table>
      </a-spin>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <merchant-pwd-modal ref="modalForm"></merchant-pwd-modal>
    <!-- 选择客服 -->
    <service-list-modal ref="serviceForm" @closeModal="closeModal"></service-list-modal>
    <!-- 选择标签 -->
    <tag-list-modal ref="tagForm" @closeModal="closeModal"></tag-list-modal>
    <!-- 选择优选 -->
    <grade-modal ref="gradeForm" @closeModal="closeModal"></grade-modal>
  </a-card>
</template>

<script>
import moment from 'moment'
import merchantPwdModal from './modules/merchantPwdModal'
import serviceListModal from './modules/serviceListModal'
import tagListModal from './modules/tagListModal'
import gradeModal from './modules/gradeModal'

import ApiTree from "@/api/merchant/merchantList";
import Category from "@/api/common/category";
import TagList from "@/api/common/tagList";
import City from "@/api/common/city";
import BusinessArea from "@/api/common/businessArea";
// import mapUl from "@/assets/map.json";
import { Slime, crud } from "@/mixins/slime";

import { initData, download } from "@/api/data";
import { parseTime, downloadFile } from "@/utils/index";
export default {
  name: "merchantList",
  mixins: [Slime],
  components: {
    merchantPwdModal,
    serviceListModal,
    tagListModal,
    gradeModal,
  },
  data() {
    return {
      confirmLoading:false,
      catUl:[
        {name: "", val:1}
      ],
      statusUl: [
        { name: "平台下架", val: 1 },
        { name: "待审核", val: 2 },
        { name: "审核通过", val: 3 },
        { name: "审核不通过", val: 4 },
        { name: "已上架", val: 6 },
      ],
      gradeUl: [
        { name: "普通店铺", val: 0 },
        { name: "优选店铺", val: 1 },
      ],
      tagUl:[
        // {name: "", val:1, choose:false}
      ],
      tagUlValue:[],
      provinceUl:[],
      cityUl:[],
      districtUl:[],
      businessUl:[],
      //客服
      serviceUl:[
        // {val:0, name:''}
      ],
      //tag展示
      tagShow: false,
      tableData: [],
      columns: [
        {
          title: "id",
          align: "center",
          dataIndex: "id",
        },
        {
          title: "商家手机",
          align: "center",
          dataIndex: "mobile",
        },
        {
          title: "标签",
          align: "center",
          dataIndex: "tagList",
          width: 100,
          scopedSlots: { customRender: 'tagList' },
        },
        {
          title: "类目",
          align: "center",
          dataIndex: "catList",
          width: 100,
          scopedSlots: { customRender: 'catList' },
        },
        {
          title: "商家名称",
          align: "center",
          width: 200,
          dataIndex: "name",
        },
        {
          title: "商家等级",
          align: "center",
          dataIndex: "grade",
          customRender: function (grade) {
            switch (grade) {
              case 0:
                return "普通店铺";
              case 1:
                return "优选店铺";
              default:
                return "未知状态";
            }
          },
        },
        {
          title: "地区",
          align: "center",
          customRender: function (status,record) {
            return record.provinceName + record.cityName + record.districtName
          },
        },
        {
          title: "地址",
          align: "center",
          width: 200,
          dataIndex: "address",
        },
        {
          title: "商圈",
          align: "center",
          width: 100,
          dataIndex: "businessAreaName",
        },
        {
          title: "审核时间",
          align: "center",
          dataIndex: "checkTime",
        },
        {
          title: "代办员名称",
          align: "center",
          dataIndex: "fromName",
        },
        {
          title: "代办员手机",
          align: "center",
          dataIndex: "fromMobile",
        },
        {
          title: "客服名称",
          align: "center",
          dataIndex: "userName",
        },
        {
          title: "店铺状态",
          align: "center",
          dataIndex: "status",
          customRender: function (status) {
            switch (status) {
              case 0:
                return "初始状态";
              case 1:
                return "平台下架";
              case 2:
                return "待审核";
              case 3:
                return "审核通过";
              case 4:
                return "审核不通过";
              case 5:
                return "已上架/歇业中";
              case 6:
                return "已上架/营业中"; 
              default:
                return "未知状态";
            }
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
    };
  },
  created() {
    crud(ApiTree);
    this.mapList()
    this.loadData();
    this.catList()
    this.serviceList()
    this.tagList()
  },
  mounted(){
    setTimeout(()=>{
      let el = document.getElementById("tag_box_flex_btn")
      let height = el.offsetHeight
      if(height >= 25){ 
        this.tagShow = false
      }else{
        this.tagShow = true
      }
    },500)
    // tag_box_flex_btn
  },
  methods: {
    // 加载表格数据
    loadData(arg) {
      this.loadDataPack(arg).then((res) => {
        let tableData = [];
        if (res.result) {
          tableData = res.result.records;
        }
        this.tableData = tableData;
      });
    },
    //分类
    catList(){
      Category.getList({pid: 0}).then((res) => {
        if (res.code == 0) {
          this.catUl = res.result.map((obj)=>{
            return obj = {
              name: obj.name, 
              val:obj.id,
            };
          })
        }
      })
    },
    //地区
    mapList(){
      let that = this
      City.regionList(0).then((res) => {
        let provinceUl = []
        let data = res.result
        data.map((obj)=>{
          let li = {
            name: obj.name,
            id: obj.id,
            val: obj.code,
          }
          provinceUl.push(li)
        })
        that.provinceUl = provinceUl
        //存在省级
        if(that.queryParam.shengId){
          City.regionList(that.queryParam.shengId).then((res) => {
            let cityUl = []
            let data = res.result
            data.map((obj)=>{
              let li = {
                name: obj.name,
                id: obj.id,
                val: obj.code,
              }
              cityUl.push(li)
            })
            that.cityUl = cityUl
            //存在市级
            if(that.queryParam.shiId){
              City.regionList(that.queryParam.shiId).then((res) => {
                let districtUl = []
                let data = res.result
                data.map((obj)=>{
                  let li = {
                    name: obj.name,
                    id: obj.id,
                    val: obj.code,
                  }
                  districtUl.push(li)
                })
                that.districtUl = districtUl
                //存在区级
                if(that.queryParam.quId){
                  let param = {
                    provinceId: that.queryParam.provinceId,
                    cityId: that.queryParam.cityId,
                    districtId: that.queryParam.districtId,
                    pageNo: 1,
                    pageSize: 30
                  }
                  BusinessArea.getList(param).then((res) => {
                    let businessUl = []
                    let data = res.result.records
                    data.map((obj)=>{
                      let li = {
                        name: obj.name,
                        val: obj.id,
                      }
                      businessUl.push(li)
                    })
                    that.businessUl = businessUl
                  })
                }
              })
            }
          })
        }
      })
    },
    //客服
    serviceList(){
      ApiTree.serviceList().then((res) => {
        let serviceUl = []
        serviceUl = res.result.map((obj)=>{
          return obj = {
            val: obj.id, 
            name: obj.nickname,
          }
        })
        this.serviceUl = serviceUl
      })
    },
    //标签
    tagList(){
      let param = {
        type:1
      }
      TagList.getList(param).then((res) => {
        let tagUl = []
        tagUl = res.result.map((obj)=>{
          return obj = {
            val: obj.id, 
            name: obj.name,
            choose: false,
          }
        })
        this.tagUl = tagUl
      })
    },
    provinceIdChange(value,option){
      let provinceId = option.data.attrs.idt
      this.queryParam.shengId = option.data.attrs.idt
      City.regionList(provinceId).then((res) => {
        let cityUl = []
        let data = res.result
        data.map((obj)=>{
          let li = {
            name: obj.name,
            id: obj.id,
            val: obj.code,
          }
          cityUl.push(li)
        })
        this.cityUl = cityUl
      })
    },
    cityIdChange(value,option){
      let cityId = option.data.attrs.idt
      this.queryParam.shiId = option.data.attrs.idt
      City.regionList(cityId).then((res) => {
        let districtUl = []
        let data = res.result
        data.map((obj)=>{
          let li = {
            name: obj.name,
            id: obj.id,
            val: obj.code,
          }
          districtUl.push(li)
        })
        this.districtUl = districtUl
      })
    },
    districtIdChange(value,option){
      this.queryParam.quId = option.data.attrs.idt
      let param = {
        provinceId: this.queryParam.provinceId,
        cityId: this.queryParam.cityId,
        districtId: this.queryParam.districtId,
        pageNo: 1,
        pageSize: 30
      }
      BusinessArea.getList(param).then((res) => {
        let businessUl = []
        let data = res.result.records
        data.map((obj)=>{
          let li = {
            name: obj.name,
            val: obj.id,
          }
          businessUl.push(li)
        })
        this.businessUl = businessUl
      })
    },
    //详情
    handleDetail(record){
      this.$router.push({ path: '/merchantDetail?id=' + record.id})
    },
    //分店
    handleBranch(record){
      this.$router.push({ query: {} })
      let pid = 0
      if(record.pid > 0){
        pid = record.pid
      }else{
        pid = record.id
      }
      this.queryParam = {
        pageNo: 1,
        pageSize: this.ipagination.pageSize,
        pid: pid
      }
      this.loadData(1)
    },
    //选择商家
    onSelectChange(selectedRowKeys){
      this.selectedRowKeys = selectedRowKeys;
    },
    //更新客服-打开
    updateUserId(){
      let merchantList = this.selectedRowKeys
      this.$refs.serviceForm.open(merchantList)
    },
    //更新标签-打开
    updateTagId(){
      let tagList = []
      if(this.selectedRowKeys.length == 1){
        let id = this.selectedRowKeys[0]
        ApiTree.getDetail(id).then((res) => {
          let data = res.result;
          tagList = data.tagList
          let merchantList = this.selectedRowKeys
          this.$refs.tagForm.open(tagList,merchantList)
        });
      }else{
        let merchantList = this.selectedRowKeys
        this.$refs.tagForm.open(tagList,merchantList)
      }
    },
    //优选店铺-打开
    setGrade(){
      let merchantList = this.selectedRowKeys
      this.$refs.gradeForm.open(merchantList)
    },
    //更新标签-执行
    // chooseTag(record){
    //   const that = this;
    //   let param = {
    //     merchantIds:this.selectedRowKeys,
    //     tagIds:record,
    //   }
    //   ApiTree.tagsUpdate(param)
    //     .then((res) => {
    //       that.$message.success('设置成功');
    //     })
    //     .finally(() => {
    //       that.selectedRowKeys = []
    //       that.closeModal();
    //     });
    // },
    //重置密码
    handlePwd(id){
      // this.$refs.modalForm.open()
      const that = this;
      ApiTree.resetPwd(id)
        .then((res) => {
          that.$message.success('重置成功');
        })
        .finally(() => {
          that.closeModal();
        });
    },
    //选择标签
    handleTagsChange(index){
      this.tagUl[index].choose = !this.tagUl[index].choose
      let tagIds = []
      for(let i=0;i<this.tagUl.length;i++){
        if(this.tagUl[i].choose){
          tagIds.push(this.tagUl[i].val)
        }
      }
      this.queryParam.tagIds = tagIds.join(',')
      // this.tagUlValue = value
      // let tagIds = value.join(',')
      // this.queryParam.tagIds = tagIds
    },
    //改变筛选时间
    panelChange(date){
      let startTime = moment(date[0]).format('YYYY-MM-DD');
      let endTime = moment(date[1]).format('YYYY-MM-DD');
      this.queryParam = {...this.queryParam, startCreateDate:startTime, endCreateDate:endTime}
    },
    funUsed(status) {
      switch (status) {
        case 0:
          return "初始状态";
        case 1:
          return "待审核";
        case 2:
          return "审核通过";
        case 3:
          return "审核不通过";
        case 4:
          return "已下架";
        case 5:
          return "已上架";
        default:
          return "未知状态";
      }
    },
    // 查 重置
    searchReset() {
      this.queryParam = {};
      this.tagUl = this.tagUl.map((obj)=>{
        return obj = {
          ...obj,
          choose:false,
        }
      })
      this.queryParamRangePicker = null;
      this.$router.push({ query: {} })
      this.loadData(1);
    },
    //导出
    searchExport(){
      this.confirmLoading = true
      let params = this.getQueryParams(); // 查询条件
      download(process.env.VUE_APP_BASE_API + "/biz/merchant/listExport", params)
        .then(result => {
          downloadFile(result, "商城数据", "xlsx");
        })
        .finally(() => {
          this.confirmLoading = false
        });
      // let params = this.getQueryParams(); // 查询条件
      // ApiTree.getListExport(params)
      //   .then((res) => {
      //     this.$message.success('导出成功');
      //   })
    },
    funTagShow(){
      this.tagShow = !this.tagShow
    },
  },
};
</script>
<style scoped>
.cat_li{
  margin: 2px;
}
</style>